/**
 * 用户router
 */
import express from "express";
import { Schema, Types } from "mongoose";
import {
  addData,
  findUserById,
  findAll,
  findUser,
  findOneByIdsync,
  updateData,
  findAccount
} from "../mdb/controlDB";
import { baseResp, userModalname, userSchematype } from "../common";
import {
  createToken,
  addLoginUser,
  getLoginUserToken,
  destroyToken,
  removeLoginUser,
  hasLoginUser,
} from "../utils/webtoken";

const router = express.Router();
export const userschema = new Schema(userSchematype);

// 新增数据
router.post("/register", function (req, res) {
  const param = req.body;
  // 注册用户只有普通权限
  param.privilege = "user";
  const addback = (data: any) => {
    if (data.success === false) {
      res.json(Object.assign({}, baseResp, { ...data }));
    } else {
      res.json(Object.assign({}, baseResp));
    }
  };

  addData({
    schematype: userschema,
    callback: addback,
    modalname: userModalname,
    param,
  });
});

// 登录
router.post("/login", function (req, res) {
  const param = req.body;
  const findback = (data: any) => {
    if (data.length) {
      const { _id, account, privilege } = data[0];
      const id: string = new Types.ObjectId(_id).toString();
      const hasLoginToken = getLoginUserToken(id);
      if (hasLoginToken) {
        destroyToken(hasLoginToken);
      }
      let token = createToken({ account });
      addLoginUser({
        id,
        token,
      });

      res.json(
        Object.assign({}, baseResp, {
          data: { id: _id, account, token, privilege },
        })
      );
    } else {
      res.json(Object.assign({}, baseResp, { success: false }));
    }
  };

  findUser({
    schematype: userschema,
    callback: findback,
    modalname: userModalname,
    param,
  });
});

router.post("/logout", function (req, res) {
  const param = req.body;
  const { id } = param;
  const findback = (data: any) => {
    if (data.length) {
      const { _id } = data[0];
      const tempId: string = new Types.ObjectId(_id).toString();
      if (id === tempId) {
        const hasLoginToken = getLoginUserToken(id);
        if (hasLoginToken) {
          destroyToken(hasLoginToken);
          removeLoginUser(id);
        }
        res.json(Object.assign({}, baseResp));
      } else {
        res.json(Object.assign({}, baseResp, { success: false }));
      }
    }
  };

  findUserById({
    schematype: userschema,
    callback: findback,
    modalname: userModalname,
    param,
  });
});

// 根据token获取用户权限
const getUserPermission = async (token: string | undefined | string[]) => {
  if (token) {
    let userId = null;
    hasLoginUser.some((item) => {
      if (item.token === token) {
        userId = item.id;
        return true;
      }
      return false;
    });
    if (userId) {
      const result: any = await findOneByIdsync({
        schematype: userschema,
        modalname: userModalname,
        param: { id: userId },
      });
      const { privilege } = result;
      return privilege;
    }
  }
  return null;
};

// 获取所有用户
router.get("/alluser", async (req, res) => {
  const userPermission = await getUserPermission(req.headers.token);

  if (userPermission !== "admin") {
    res.status(401).send("invalid token");
    return;
  }

  const findBack = (data: any[]) => {
    let tempData: any[] = [];
    if (data && data.length) {
      data.forEach((item) => {
        const { account, privilege, _id } = item;
        tempData.push({
          account,
          privilege,
          id: _id,
        });
      });
    }
    res.json(Object.assign({}, baseResp, { data: tempData }));
  };
  findAll({
    schematype: userschema,
    callback: findBack,
    modalname: userModalname,
  });
});

// 修改权限
router.post("/modifypermission", async (req, res) => {
  const param = req.body;
  const userPermission = await getUserPermission(req.headers.token);

  // 自己不能编辑自己
  let userId = null;
  hasLoginUser.some((item) => {
    if (item.token === req.headers.token) {
      userId = item.id;
      return true;
    }
    return false;
  });

  // 普通用户无法编辑权限
  // 管理员自己不能编辑自己
  if (!userId || userId === param.id || userPermission !== "admin") {
    res.status(402).send(
      Object.assign({}, baseResp, {
        success: true,
        message: "permission error",
      })
    );
    return;
  }

  const editback = (data: any) => {
    res.json(Object.assign({}, baseResp));
  };

  updateData({
    schematype: userschema,
    callback: editback,
    modalname: userModalname,
    param,
  });
});

router.post("/checkuser", async (req, res) => {
  const param = req.body;
  const accountinfo = await findAccount({
    schematype: userschema,
    modalname: userModalname,
    param,
  });
  if (!accountinfo) {
    res.send(
      Object.assign({}, baseResp, {
        success: false,
        message: "account or email error",
      })
    );
  } else {
    res.json(Object.assign({}, baseResp, { data: { id: accountinfo._id } }));
  }
});

router.post("/changepassword", async (req, res) => {
  const param = req.body;

  const editback = (data: any) => {
    res.json(Object.assign({}, baseResp));
  };

  updateData({
    schematype: userschema,
    callback: editback,
    modalname: userModalname,
    param,
  });
});

export default router;
